package com.copa.gameStore.service.impl;

import com.copa.gameStore.domain.GameGoods;
import com.copa.gameStore.dto.GameGoodsDto;
import com.copa.gameStore.mapper.GameGoodsMapper;
import com.copa.gameStore.service.GameGoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.ValidationException;
import java.util.Objects;

/**
 * @author copa
 * @createDate 2022-09-27 09:55
 * @function
 */
@Service
public class GameGoodsServiceImpl implements GameGoodsService {

    @Resource
    private GameGoodsMapper gameGoodsMapper;

    @Override
    public void add(GameGoodsDto gameGoodsDto) {
        GameGoods gameGoods = new GameGoods();
        // 添加时不可能有id
        gameGoodsDto.setId(null);
        BeanUtils.copyProperties(gameGoodsDto, gameGoods);
        if (gameGoodsMapper.insert(gameGoods) <= 0) {
            throw new RuntimeException();
        }
    }

    @Override
    public void modify(GameGoodsDto gameGoodsDto) {
        GameGoods gameGoods = new GameGoods();
        BeanUtils.copyProperties(gameGoodsDto, gameGoods);
        if (gameGoodsMapper.updateById(gameGoods) <= 0) {
            throw new RuntimeException();
        }
    }

    @Override
    public Boolean validateGoods(Long id) {
        GameGoods gameGoods = gameGoodsMapper.selectById(id);
        if (Objects.isNull(gameGoods)) {
            // 如果该商品不存在
            return false;
        }
        if (!gameGoods.getIsEnabled()) {
            // 如果该商品未上架
            return false;
        }
        return true;
    }

    @Override
    public void stock(Long id, Integer num) {
        synchronized (id) {
            if (num != 0) {
                // 库存变动
                GameGoods gameGoods = gameGoodsMapper.selectById(id);
                if (gameGoods.getNum() - num < 0) {
                    throw new ValidationException("该商品库存不足~无法下单噢~请检查购物车吧~");
                }
                gameGoods.setNum(gameGoods.getNum() - num);
                if (gameGoodsMapper.updateById(gameGoods) <= 0) {
                    throw new RuntimeException();
                }
            }
        }
    }
}
